package com.dacd.soundanalysis.thread

import android.content.Context
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import android.os.Handler
import android.util.Log
import com.alibaba.fastjson.JSON
import com.dacd.soundanalysis.bean.SoundBean
import com.dacd.soundanalysis.filehelper.FileConstants
import com.dacd.soundanalysis.filehelper.FileHelper
import com.dacd.soundanalysis.sharepreferences.ShareConstants
import com.dacd.soundanalysis.sharepreferences.SharePreHelper
import com.dacd.soundanalysis.soundhelper.FrequencyScanner
import com.dacd.soundanalysis.soundhelper.SoundConstants
import kotlin.math.sqrt

class LearnRecThread(context: Context, handler: Handler) : Thread() {

    private var audioRecord: AudioRecord? = null//录音类
    private var minBufferSize: Int = 0
    private var isRecording = false
    private var recordList: ArrayList<SoundBean>? = null
    private var currentVolume: Double = 0.0
    private var currentFrequency: Double = 0.0
    private var context:Context? = null
    private var handler:Handler? = null

    init {
        this.context = context
        this.handler = handler
    }

    fun initAudioLearnThread(): Boolean {
        minBufferSize = AudioRecord.getMinBufferSize(
            SoundConstants.SAMPLE_RATE,
            AudioFormat.CHANNEL_IN_MONO,
            AudioFormat.ENCODING_PCM_16BIT
        )
        audioRecord = AudioRecord(
            MediaRecorder.AudioSource.MIC,
            SoundConstants.SAMPLE_RATE
            ,
            AudioFormat.CHANNEL_IN_MONO,
            AudioFormat.ENCODING_PCM_16BIT
            , minBufferSize
        )
        minBufferSize = 1024
        if (AudioRecord.ERROR_BAD_VALUE == minBufferSize || AudioRecord.ERROR == minBufferSize) {
            //设备不支持
            return false
        }
        if (audioRecord!!.state != AudioRecord.STATE_INITIALIZED) {
            return false
        }
        recordList = ArrayList()
        return true
    }

    override fun run() {
        //开始录音
        isRecording = true
        val bufferRead = ShortArray(minBufferSize)
        audioRecord!!.startRecording()
//        val testMillis = System.currentTimeMillis()
        while (isRecording && audioRecord!!.recordingState == AudioRecord.RECORDSTATE_RECORDING) {
            var sum: Double = 0.0
            val readSize = audioRecord!!.read(bufferRead, 0, minBufferSize)
            for (i in 0 until readSize) {
                sum += bufferRead[i] * bufferRead[i]
            }
            if (readSize > 0) {
                val amplitude: Double = sum / readSize
                currentVolume = sqrt(amplitude)
            }
            if (currentVolume > SoundConstants.VOLUME_LIMIT) {
                handler!!.sendEmptyMessage(1)
                currentFrequency =
                    FrequencyScanner().extractFrequency(bufferRead, SoundConstants.SAMPLE_RATE)
                val soundBean = SoundBean()
                soundBean.frequency = currentFrequency.toInt()
                if(recordList!!.size > 0) {
                    soundBean.timeMillis = System.currentTimeMillis() - recordList!![0].timeMillis
                    soundBean.isHead = false
                } else {
                    soundBean.isHead = true
                    soundBean.timeMillis = System.currentTimeMillis()
                }
                recordList!!.add(soundBean)
            }
        }
    }

    /**
     * 停止录音
     */
    fun stopRecord() {
        isRecording = false
        if (audioRecord != null) {
            if (audioRecord!!.getState() == AudioRecord.STATE_INITIALIZED) {//初始化成功
                audioRecord!!.stop()
            }
            if (audioRecord != null) {
                audioRecord!!.release()
            }
        }
        if (recordList!!.size > 5) {
            val nowTimes = SharePreHelper.getSPInt(context!!, ShareConstants.SAVE_TIMES)!!
            val msg = handler!!.obtainMessage(3)
            msg.arg1 = nowTimes + 1
            handler!!.sendMessage(msg)
            SynthesisThread(context!!, recordList!!).start()
        }
    }
}